package com.codec;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;


public class MessageDecoder extends CumulativeProtocolDecoder {

	private final Charset charset;

	public MessageDecoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		CharsetDecoder cd = charset.newDecoder();
		if (in.remaining() > 0) {
			byte[] sizeBytes = new byte[4];
			in.mark();
			in.get(sizeBytes);
			int size = ByteUtil.getInt(sizeBytes, 0);
			if (size - 4 > in.remaining()) {
				in.reset();
				return false;
			} else {
				byte[] bytContent = new byte[size - 4];
				in.get(bytContent, 0, size - 4);
				int type = ByteUtil.getInt(bytContent, 0);
				int requestid = ByteUtil.getInt(bytContent, 4);

//				System.out.println("");
//				System.out.println("=================================================================");
//				System.out.println("type:" + type + ",bytContent:" + bytContent);
//				System.out.println("=================================================================");
//				System.out.println("");

				String content = new String(bytContent, 8, size - 12, "utf-8");
				if (null != content && content.length() > 0) {		    		
					MessagePack msgPack = new MessagePack(type, requestid, content);
					out.write(msgPack);
				} else {
					MessagePack msgPack = new MessagePack(type, requestid, "");
					out.write(msgPack);
				}
				if (in.remaining() > 0) {
					return true;
				}
			}
		}
		return false;
	}

}